package com.member.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.member.dao.MemberDao;
import com.member.domain.MemberCommand;
import com.member.validator.MemberValidator;

@Controller
public class MyInfoUpdateController {

	@Autowired
	private MemberDao memberDao;
	
	
	@RequestMapping(value="/shop/updateMyInfo.do",method=RequestMethod.GET)
	public ModelAndView process(HttpSession session){
		
		String userId = (String)session.getAttribute("userId");
		
		MemberCommand member = memberDao.selectMyInfo(userId);
		
		ModelAndView mav = new ModelAndView();
		
		if(userId.equals("admin")){
			mav.setViewName("adminInfoPage");
		}else{
			mav.setViewName("myInfoUpdate");
		}
		mav.addObject("member", member);
		
		return mav;
	}
	
	@ModelAttribute
	public MemberCommand formBacking(){
		
		return new MemberCommand();
	}
	
	@RequestMapping(value="/shop/updateMyInfo.do",method=RequestMethod.POST)
	public String submit(@RequestParam("passwd2") String passwd2, MemberCommand memberCommand, BindingResult result){
		
		new MemberValidator().validate(memberCommand, result);
		
		if(result.hasErrors()){
			
			return "myInfoUpdate";
		}
		
		if(!memberCommand.getM_passwd().equals(passwd2)){
			result.reject("invalidPassword", new Object[]{""}, null);
			return "myInfoUpdate";
		}
		
		memberDao.updateMyInfo(memberCommand);
		return "redirect:/shop/myInfo.do";
	}
	
}
